﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace ImgThumb
{
    public partial class MainForm : Form
    {
        private string _saveFilePath = Application.StartupPath;//文件保存路径
        private List<string> _list = new List<string>();//图片列表
        private bool _isReName = false;//是否重命名
        private string _prefix = "";//后缀名
        private Thread _tWork;//处理方法的线程
        //AutoResetEvent _resetEvent = new AutoResetEvent(false);//通知等待线程信号

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            this.cbb_Prefix.SelectedIndex = 0;
            this.cbb_MaxW.SelectedIndex = 3;

            this.timer1.Interval = 50;
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            this.timer1.Start();
        }

        #region 数据初始化

        public void DataInit()
        {
            //数据初始化
            ApplicationModel.SumCount = 0;
            ApplicationModel.CurrentNumber = 0;
            ApplicationModel.AddCount = 0;
            ApplicationModel.UpdateCount = 0;
            ApplicationModel.SuccessCount = 0;
            ApplicationModel.ErrCount = 0;
            ApplicationModel.ErrMsg = "";
            //ApplicationModel.LimitCpu = this.chk_LimCPU.Checked;

            string width = this.cbb_MaxW.SelectedItem.ToString().Trim().Replace("像素", "");
            if (!width.Contains("限制"))
            {
                ApplicationModel.MaxWidth = Convert.ToInt32(width);
            }

            tsProgressBar.Maximum = 0;
            tsProgressBar.Value = 0;
            this.lblProgressMsg.Text = "";
            this._isReName = this.chk_Rename.Checked;

            this._prefix = this.cbb_Prefix.SelectedItem.ToString();
            this._prefix = this._prefix.Contains("默认") ? "" : this._prefix;
        }
        #endregion

        #region 每50毫秒执行一次

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if (ApplicationModel.SumCount != 0)
                {
                    this.tsProgressBar.Maximum = ApplicationModel.SumCount;
                    if (ApplicationModel.SuccessCount != 0)
                    {
                        tsProgressBar.Value = ApplicationModel.SuccessCount;
                        lblProgressMsg.Text = "正在处理第" + ApplicationModel.CurrentNumber + "/" + ApplicationModel.SumCount + "张,成功"
                            + ApplicationModel.SuccessCount + "张...";
                    }
                    if (ApplicationModel.CurrentNumber == ApplicationModel.SumCount)
                    {
                        lblProgressMsg.Text = "处理完毕，成功数量：" + ApplicationModel.SuccessCount + "/" + ApplicationModel.SumCount + "！";
                    }
                }
                if ((ApplicationModel.ErrMsg + "").Length > 0)
                {
                    lblProgressMsg.Text = ApplicationModel.ErrMsg;
                }
                if (this._tWork == null || this._tWork.ThreadState == System.Threading.ThreadState.Stopped)//线程已经终止
                {
                    this.btn_Cancle.Enabled = false;
                    this.btnAction.Enabled = true;
                }
                else
                {
                    this.btnAction.Enabled = false;
                }
            }
            catch (Exception)
            {
                timer1.Enabled = false;
            }
        }
        #endregion

        #region 快捷键
        //退出
        private void tsmiExit_Click(object sender, EventArgs e)
        {
            icnTray.Visible = false;//防止系统托盘程序运行的时候会产生多个托盘图标
            Application.Exit();
        }
        //显示 隐藏窗体
        private void tsmiShowIt_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = true;
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
                this.tsmiShowIt.Text = "隐藏";
                return;
            }
            if (this.Visible)
            {
                this.Visible = false;
                this.tsmiShowIt.Text = "显示";
            }
            else
            {
                this.Visible = true;
                this.tsmiShowIt.Text = "隐藏";
            }
        }
        //记事本
        private void tsbtn_Note_Click(object sender, EventArgs e)
        {
            Process.Start("notepad.exe");
        }
        //Excel
        private void tsbtn_Excel_Click(object sender, EventArgs e)
        {
            try
            {
                Process.Start("excel.exe");
            }
            catch (Exception)
            {
                try
                {
                    Process.Start("et.exe");
                }
                catch (Exception)
                {
                    MessageBox.Show("当前系统没有发现可执行的Excel文件, 如需使用表格功能请先安装office或wps", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
        //Word
        private void tsbtn_Word_Click(object sender, EventArgs e)
        {
            try
            {
                Process.Start("winword.exe");
            }
            catch (Exception)
            {
                try
                {
                    Process.Start("wps.exe");
                }
                catch (Exception)
                {
                    MessageBox.Show("当前系统没有发现可执行的word文件, 如需使用表格功能请先安装office或wps", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
        //计算器
        private void tsbtn_Calculate_Click(object sender, EventArgs e)
        {
            Process.Start("calc.exe");
        }
        //退出
        private void tsbtn_Quit_Click(object sender, EventArgs e)
        {
            icnTray.Visible = false;//防止系统托盘程序运行的时候会产生多个托盘图标
            Application.Exit();
        }
        //文件更名
        private void tsbtn_Rename_Click(object sender, EventArgs e)
        {
            UI.ReName rename = new UI.ReName();
            rename.Show();
        }
        //帮助
        private void tsbtn_Help_Click(object sender, EventArgs e)
        {
            UI.Helper help = new UI.Helper();
            help.Show();
        }
        #endregion

        #region 拖拽
        //保存路径
        private void txt_SavePath_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = ((string[])e.Data.GetData(DataFormats.FileDrop));
            if (files.Length > 0 && !File.Exists(files[0]))
            {
                this.txt_SavePath.Text = files[0] + "\\";
            }
        }

        private void txt_SavePath_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Link;
            else e.Effect = DragDropEffects.None;
        }

        private void lv_list_DragDrop(object sender, DragEventArgs e)
        {
            string[] imgs = ((string[])e.Data.GetData(DataFormats.FileDrop));
            if (imgs == null || imgs.Length == 0)
            {
                return;
            }
            if (imgs.Length == 1 && !File.Exists(imgs[0]))//文件夹
            {
                this._list = Common.GetPath(imgs[0]);
            }
            else//文件列表
            {
                for (int i = 0; i < imgs.Length; i++)
                {
                    if (!Common.IsImage(imgs[i]))
                    {
                        continue;
                    }
                    if (!this._list.Contains(imgs[i]))
                    {
                        this._list.Add(imgs[i]);
                    }
                }
            }
            if (this._list.Count > 0)
            {
                this.lbl_ListPoint.Visible = false;
                string name = "";
                ListViewItem lvi = null;
                foreach (string k in this._list)
                {
                    name = k.Substring(k.LastIndexOf("\\") + 1, k.Length - 1 - k.LastIndexOf("\\"));

                    lvi = new ListViewItem(new string[] { name, k });
                    lvi.UseItemStyleForSubItems = false;
                    lvi.SubItems[1].BackColor = Color.AliceBlue;
                    this.lv_list.Items.Add(lvi);
                }
                this.lblProgressMsg.Text = "共有" + _list.Count + "张图片！";
            }
            else
            {
                this.lbl_ListPoint.Visible = true;
            }
        }

        private void lv_list_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Link;
            else e.Effect = DragDropEffects.None;
        }

        #endregion

        #region 操作

        private void btnSaveImg_Click(object sender, EventArgs e)
        {
            fbdImg.ShowDialog();
            fbdImg.ShowNewFolderButton = true;
            this.txt_SavePath.Text = fbdImg.SelectedPath + "\\";
        }
        //暂停
        private void btn_Cancle_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.btn_Cancle.Text.Equals("暂停"))
                {
                    this.btn_Cancle.Text = "启动";
                    if (this._tWork.ThreadState == System.Threading.ThreadState.Background)
                    {
                        this._tWork.Suspend();
                    }
                }
                else
                {
                    this.btn_Cancle.Text = "暂停";
                    if (this._tWork.ThreadState == (System.Threading.ThreadState.Suspended | System.Threading.ThreadState.Background))
                    {
                        this._tWork.Resume();
                    }
                }
            }
            catch (Exception)
            {

            }
        }
        //开始转换
        private void btnAction_Click(object sender, EventArgs e)
        {
            DataInit();
            if (this.lv_list.Items.Count == 0)
            {
                ApplicationModel.ErrMsg = "列表中还没有文件！";
                return;
            }
            if (txt_SavePath.Text.Trim().Length == 0)
            {
                ApplicationModel.ErrMsg = "请选择图片文件夹路径！";
                return;
            }
            this.btn_Cancle.Enabled = true;
            this.txt_SavePath.Text = this.txt_SavePath.Text.Trim().EndsWith("\\") ? this.txt_SavePath.Text.Trim() : this.txt_SavePath.Text.Trim() + "\\";
            ApplicationModel.SumCount = this._list.Count;

            _tWork = new Thread(ImageZoom);
            _tWork.IsBackground = true;
            _tWork.Start();
        }
        //清空列表
        private void btn_ClearList_Click(object sender, EventArgs e)
        {
            this._list.Clear();
            this.lv_list.Items.Clear();
            this.lbl_ListPoint.Visible = true;
            this.btn_Cancle.Enabled = false;
            this.lblProgressMsg.Text = "列表中没有图片！";
            tsProgressBar.Maximum = 0;
            tsProgressBar.Value = 0;
        }
        //移除
        private void 移除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string tem = "";
            if (this.lv_list.SelectedItems.Count > 0)
            {
                this.btn_Cancle.Enabled = true;
                tem = this.lv_list.SelectedItems[0].SubItems[0].Text;
                this._list.Remove(tem);
                this.lv_list.SelectedItems[0].Remove();
                this.lblProgressMsg.Text = "共有" + _list.Count + "张图片！";
            }
            if (this._list.Count == 0)
            {
                this.lbl_ListPoint.Visible = true;
                this.lblProgressMsg.Text = "列表中没有图片！";
                this.btn_Cancle.Enabled = false;
            }
        }
        private void ImageZoom()
        {
            Common.GetAll(this._list, txt_SavePath.Text.Trim(), this._isReName, this._prefix);
        }

        #endregion

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (icnTray != null)
            {
                icnTray.Dispose();//销毁托盘图标
            }
        }

        private void 软件说明ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("notepad.exe", Application.StartupPath + "\\" + "说明.txt");
        }
    }
}
